<!--
 * @Description: 临建设施台账
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2022-03-18 14:48:33
 * @LastEditTime: 2022-03-29 11:37:22
 * @FilePath: \cscec-pms-admin\src\views\project\plannManagement\plannTableComponents\components\TemporaryFacilitiesLedger.vue
-->
<template>
  <a-card>
    <title-name title="临建设施台账" />
    <a-button
      v-if="info.pageType !== 'detail'"
      type="primary"
      class="add"
      @click="handleAdd"
    >
      增行
    </a-button>
    <a-button
      v-if="info.pageType !== 'detail'"
      class="add"
      @click="handleDelete"
    >
      删除行
    </a-button>
    <a-table
      ref="table"
      :columns="columns"
      :data-source="data"
      :pagination="false"
      bordered
      :loading="loading"
      row-key="id"
      :scroll="{x:2080}"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <template
        v-for="{dataIndex} in columnsFlat"
        :slot="dataIndex"
        slot-scope="text,record,index"
      >
        <!-- 查看 -->
        <span
          v-if="info.pageType === 'detail'"
          :key="dataIndex"
        >
          <template v-if="dataIndex === 'departmentId'">
            {{ record.departmentName }}
          </template>
          <template v-else-if="dataIndex === 'unitId'">
            {{ record.unitName }}
          </template>
          <template v-else-if="dataIndex === 'implementationStatus'">
            {{ implementationStatusList.find(el=>el.value === record[dataIndex]) ? implementationStatusList.find(el=>el.value === record[dataIndex]).label : '' }}
          </template>
          <template v-else-if="dataIndex === 'isDisposal'">
            {{ isDisposalList.find(el=>el.value === record[dataIndex]) ? isDisposalList.find(el=>el.value === record[dataIndex]).label : '' }}
          </template>
          <template v-else>
            {{ record[dataIndex] }}
          </template>
        </span>
        <!-- 查看 -->
        <!-- 编辑 -->
        <template v-else>
          <!-- 购置日期 -->
          <a-date-picker
            v-if="dataIndex === 'acquisitionDate'"
            :key="dataIndex"
            v-model="record[dataIndex]"
            placeholder="请选择"
            class="input"
          />
          <!-- 购置日期 -->
          <!-- 折旧使用年限(年)/已使用年限(年)/原值(万元)/累计折旧(万元)-->
          <BaseInputNumber
            v-else-if=" ['usefulLife','serviceLife','originalValue','bookValue'].includes(dataIndex)"
            :key="dataIndex"
            v-model="record[dataIndex]"
            :precision="2"
            class="input"
            @blur="()=>{handleCalcNetValue(record,dataIndex,index)}"
          />
          <!-- 折旧使用年限(年)/已使用年限(年)/原值(万元)/累计折旧(万元)-->
          <!-- 使用单位或项目名称 -->
          <SelectCompanyAndProject
            v-else-if="dataIndex === 'unitId'"
            :key="dataIndex"
            v-model="record[dataIndex]"
            class="width-100 input"
            :auto-select="true"
            @onSelectChange="(v)=>{handleIdChange(v,record,'unitName')}"
          />
          <!-- 使用单位或项目名称 -->
          <!-- 实施状态 -->
          <a-select
            v-else-if="dataIndex === 'implementationStatus'"
            :key="dataIndex"
            v-model="record[dataIndex]"
            placeholder="请选择"
            class="width-100 input"
          >
            <a-select-option
              v-for="{value,label} in implementationStatusList"
              :key="value"
              :value="value"
            >
              {{ label }}
            </a-select-option>
          </a-select>
          <!-- 实施状态 -->
          <!-- 责任保管部门 -->
          <SelectOrgDepartment
            v-else-if="dataIndex === 'departmentId'"
            :key="dataIndex"
            v-model="record[dataIndex]"
            :org-id="record.unitId"
            class="width-100 input"
            :is-auto-select-me="true"
            @onSelectChange="(v)=>{handleIdChange(v,record,'departmentName')}"
          />
          <!-- 责任保管部门 -->
          <!-- 是否拟定后续处置方案 -->
          <a-select
            v-else-if="dataIndex === 'isDisposal'"
            :key="dataIndex"
            v-model="record[dataIndex]"
            placeholder="请选择"
            class="width-100 input"
            @change="handleIsDisposal"
          >
            <a-select-option
              v-for="{value,label} in isDisposalList"
              :key="value"
              :value="value"
            >
              {{ label }}
            </a-select-option>
          </a-select>
          <!-- 是否拟定后续处置方案 -->
          <!-- 处置方式 -->
          <BaseInput
            v-else-if="dataIndex === 'disposalWay'"
            :key="dataIndex"
            v-model="record[dataIndex]"
            :class="record.isDisposal === 1?'input':''"
          />
          <!-- 处置方式 -->
          <BaseInput
            v-else
            :key="dataIndex"
            v-model="record[dataIndex]"
            :class="dataIndex === 'remark' || dataIndex === 'netValue'?'':'input'"
            :max-length="300"
            :disabled="dataIndex === 'netValue'"
          />
        </template>
        <!-- 编辑 -->
      </template>
    </a-table>
  </a-card>
</template>
<script>
import { scheme } from '@/api/project/plannManagement/plannTableSummary'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import SelectOrgDepartment from '@/components/Select/SelectOrgDepartment'
export default {
  name: 'TemporaryFacilitiesLedger' + Date.now(),
  components: {
    SelectCompanyAndProject,
    SelectOrgDepartment
  },
  data() {
    return {
      // 表头
      columns: [
        {
          title: '序号',
          width: 80,
          align: 'center',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '设施基本情况',
          children: [
            {
              title: '名称',
              dataIndex: 'name',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'name' }
            },
            {
              title: '型号',
              dataIndex: 'model',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'model' }
            },
            {
              title: '购置日期',
              dataIndex: 'acquisitionDate',
              align: 'center',
              width: 150,
              scopedSlots: { customRender: 'acquisitionDate' }
            },
            {
              title: '折旧使用年限(年)',
              dataIndex: 'usefulLife',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'usefulLife' }
            },
            {
              title: '已使用年限(年)',
              dataIndex: 'serviceLife',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'serviceLife' }
            }
          ]
        },

        {
          title: '账面价值',
          children: [
            {
              title: '原值(万元)',
              dataIndex: 'originalValue',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'originalValue' }
            },
            {
              title: '累计折旧(万元)',
              dataIndex: 'bookValue',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'bookValue' }
            },
            {
              title: '净值(万元)',
              dataIndex: 'netValue',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'netValue' }
            }
          ]
        },
        {
          title: '设施现状',
          children: [
            {
              title: '使用单位或项目名称',
              dataIndex: 'unitId',
              align: 'center',
              width: 160,
              scopedSlots: { customRender: 'unitId' }
            },
            {
              title: '所在城市',
              dataIndex: 'city',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'city' }
            },
            {
              title: '存放地点',
              dataIndex: 'storagePlace',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'storagePlace' }
            },
            {
              title: '实施状态',
              dataIndex: 'implementationStatus',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'implementationStatus' }
            },
            {
              title: '责任保管部门',
              dataIndex: 'departmentId',
              align: 'center',
              width: 160,
              scopedSlots: { customRender: 'departmentId' }
            }
          ]
        },
        {
          title: '后续处置计划',
          children: [
            {
              title: '是否拟定后续处置方案',
              dataIndex: 'isDisposal',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'isDisposal' }
            },
            {
              title: '处置方式',
              dataIndex: 'disposalWay',
              align: 'center',
              width: 120,
              scopedSlots: { customRender: 'disposalWay' }
            }
          ]
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 120,
          scopedSlots: { customRender: 'remark' }
        }
      ],
      // 表数据
      data: [],
      // 选中项
      selectedRowKeys: [],
      // 必填项
      required: ['name', 'model', 'acquisitionDate', 'usefulLife', 'serviceLife', 'originalValue', 'bookValue', 'unitId', 'city', 'storagePlace', 'implementationStatus', 'departmentId', 'isDisposal', 'disposalWay'],
      // 加载
      loading: false,
      // 实施状态
      implementationStatusList: [
        {
          value: '0',
          label: '在用'
        },
        {
          value: '1',
          label: '维修'
        },
        {
          value: '2',
          label: '保养'
        },
        {
          value: '3',
          label: '其他'
        }
      ],
      // 是否拟定后续处置方案
      isDisposalList: [
        {
          value: 0,
          label: '否'
        },
        {
          value: 1,
          label: '是'
        }
      ]
    }
  },
  computed: {
    // 地址携带信息
    info() {
      return this.$route.query
    },
    // 表格成员扁平化
    columnsFlat() {
      const flat = (columns, list = []) => {
        columns.forEach((el) => {
          if (el.children && el.children.length > 0) {
            const item = JSON.parse(JSON.stringify(el))
            delete item.children
            flat(el.children, list)
          } else {
            list.push(el)
          }
        })
        return list
      }
      return flat(this.columns)
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    /**
     * @description: 获取数据
     * @param {void}
     * @return {void}
     */
    async getData() {
      this.data = []
      const { id, version } = this.info
      this.loading = true
      const { code, data } = await scheme.querySchemeTemporaryFacilitiesLedgerDetail({
        latestData: version ? false : true,
        schemeDetailId: id,
        version
      })
      if (code === 200 && data.length > 0) {
        // 已有数据
        this.data = data
      } else {
        // 没有数据
        this.handleAdd()
      }
      this.loading = false
    },
    /**
     * @description: 选中项改变
     * @param {string} selectedRowKeys 选中项id
     * @return {void}
     */
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * @description: 新增行
     * @param {void}
     * @return {void}
     */
    handleAdd() {
      const data = {}
      this.columnsFlat.forEach((el) => {
        if (el.dataIndex) {
          if (el.dataIndex === 'implementationStatus') {
            data[el.dataIndex] = '0'
          } else if (el.dataIndex === 'isDisposal') {
            data[el.dataIndex] = 1
          }
        } else {
          data.id = 'temp' + Date.now()
        }
      })
      data.departmentName = null
      data.unitName = null
      this.data.push(data)
    },
    /**
     * @description: 是否拟定后续处置方案改变
     * @param {number} 值
     * @return {void}
     */
    handleIsDisposal(v) {
      if (v) {
        this.required.push('disposalWay')
      } else {
        this.required.splice(this.required.indexOf('disposalWay'), 1)
      }
    },
    /**
     * @description: 删除行
     * @param {void}
     * @return {void}
     */
    handleDelete() {
      this.data = this.data.filter((el) => !this.selectedRowKeys.includes(el.id))
      this.selectedRowKeys = []
    },
    /**
     * @description: 计算净值
     * @param {object} record 行数据
     * @param {string} dataIndex 列名称
     * @param {number} index 行索引
     * @return {void}
     */
    handleCalcNetValue(record, dataIndex, index) {
      if (['originalValue', 'bookValue'].includes(dataIndex)) {
        if (typeof record.originalValue === 'number' && typeof record.bookValue === 'number') {
          this.$set(this.data, index, { ...record, netValue: record.originalValue.sub(record.bookValue) })
        } else {
          this.$set(this.data, index, { ...record, netValue: null })
        }
      }
    },
    /**
     * @description: 表格校验
     * @param {void}
     * @return {boolean} 是否通过校验
     */
    verify() {
      return !this.data.some((el) => {
        for (let item in this.required) {
          if ((el[this.required[item]] ?? '') === '') {
            return true
          }
        }
      })
    },
    /**
     * @description: 保存草稿
     * @param {object} baseInfo 基本信息
     * @return {void}
     */
    TemporaryFacilitiesLedgerSaveDrafts(baseInfo) {
      this.handleSubmit(0, baseInfo)
    },
    /**
     * @description: 提交
     * @param {object} baseInfo 基本信息
     * @return {void}
     */
    TemporaryFacilitiesLedgerSubmit(baseInfo) {
      if (this.verify()) {
        const vm = this
        this.$confirm({
          title: '温馨提示',
          content: '请确认是否提交？',
          onOk() {
            vm.handleSubmit(1, baseInfo)
          }
        })
      } else {
        this.$confirm({
          title: '温馨提示',
          content: '请将数据填写完整'
        })
      }
    },
    /**
     * @description: 数据提交
     * @param {number} status 状态码
     * @return {void}
     */
    handleSubmit(status, baseInfo) {
      const { id: schemeDetailId, pageType } = this.info
      scheme
        .batchUpdateSchemeTemporaryFacilitiesLedger({
          changed: pageType === 'change',
          list: this.data,
          schemeDetailId,
          status
        })
        .then(({ code }) => {
          if (code === 200) {
            this.$message.success('操作成功')
            baseInfo.schemeDetailId = schemeDetailId
            baseInfo.status = status
            this.$emit('updateBasicDetail', baseInfo)
            this.getData()
            if (status === 1) {
              this.$close()
            }
          }
        })
    },
    /**
     * @description: 使用单位或项目名称设置
     * @param {object} v 选中项对象
     * @param {void} record 行数据
     * @param {void} dataIndex 列名称
     * @return {void}
     */
    handleIdChange(v, record, dataIndex) {
      record[dataIndex] = v.name
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.add {
  margin-right: 20px;
  margin-bottom: 20px;
}
@{deep}.input {
  .ant-input,
  .ant-input-number,
  .ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
}
.width-100 {
  width: 100%;
}
</style>
